
import {Users} from '../imports/api/users/users.js';
import {Transactions} from '../imports/api/transaction/transactions.js';
import { Session } from 'meteor/session'

let faker = require('faker/locale/zh_CN');
const https = require('https');
const fs = require('fs');
const path = require("path");

//如果定义了path_avatar，表明要下载图标以离线使用, 否则使用互联网图标
//const path_avatar = '/Users/jiangbuyun/avatar';
const path_avatar = false;
const count_user = 10;
const count_trans = 5;
const count_unconfirm = 2;
let fus=[];

export function fake_user(){
    return fus[0];
}

export function sysLogin (username,pwd){
    query={
            $and: 
            [
              {"title":username},  
              {"password":pwd} 
            ]
          };
   fus = Users.find(query).fetch();
   if(fus.length == 1){
        return fus[0];
   }
};


//递归创建目录 同步方法  
function mkdirsSync(dirname) {  
    //console.log(dirname);  
    if (fs.existsSync(dirname)) {  
        return true;  
    } else {  
        if (mkdirsSync(path.dirname(dirname))) {  
            fs.mkdirSync(dirname);  
            return true;  
        }  
    }  
}  
function dl(pos){
    if(pos>= fus.length)
        return;
    let fua = fus[pos].av;
    console.log('\\\\\\\\\\\\======='+fua);
    let pos1 = fua.indexOf('/',10);
    let fpath = path_avatar+fua.substring(pos1).replace(/\//g,path.sep);
    console.log('fpath-'+pos+ ':'+fpath);
    let dir = path.dirname(fpath);
    mkdirsSync(dir);
    https.get(fua, (res) => {
        console.log('statusCode:', res.statusCode);
        console.log('headers:', res.headers);
        let imagedata = ''
        res.setEncoding('binary')
        res.on('data', function(chunk){
            imagedata += chunk
        })
        res.on('end', function(){
            fs.writeFile(fpath, imagedata, 'binary', function(err){
                if (err) {
                     console.error(err);
                }
                dl(pos+1);
            })
        })
    }).on('error', (e) => {
        console.error(e);
        return dl(pos+1);
    });    
}
//下载头像到本地
function downloadAvatars(){
    dl(0);
}

export function fake() {
    //data exists, no need for fake
    fus = Users.find().fetch();
    if (fus.length > 0) {
        return fus[0];
    }

    let f_av = faker.image.avatar();
    let pos1 = f_av.indexOf('/',10);
    let f_avatar = path_avatar?f_av.substring(pos1):f_av;

     let f_av1 = faker.image.avatar();
    let pos2 = f_av1.indexOf('/',10);
    let f_avatar1 = path_avatar?f_av1.substring(pos2):f_av1;


     let f_av2 = faker.image.avatar();
    let pos3 = f_av2.indexOf('/',10);
    let f_avatar2 = path_avatar?f_av2.substring(pos3):f_av2;


     let f_av3 = faker.image.avatar();
    let pos4 = f_av3.indexOf('/',10);
    let f_avatar3 = path_avatar?f_av3.substring(pos4):f_av3;

     let f_av4 = faker.image.avatar();
    let pos5 = f_av4.indexOf('/',10);
    let f_avatar4 = path_avatar?f_av4.substring(pos5):f_av4;

    fus = [
        {
            title: "县扶贫办",
            createdAt: faker.date.recent(),
            userId: "xian",
            av:f_av,
            avatar: f_avatar,//"https://s3.amazonaws.com/uifaces/faces/twitter/brenmurrell/128.jpg",
            desc: "负责扶贫项目的审批和资金的发放",
            createdBy:"",
            balance: 0,
            status : "已认证",
             utype : "用户"
        },
        {
            title: "乡扶贫办",
            createdAt: faker.date.recent(),
            userId: "xiang",
            av:f_av1,
            avatar: f_avatar1,//"https://s3.amazonaws.com/uifaces/faces/twitter/brenmurrell/128.jpg",
            desc: "负责管理扶贫项目和具体实施",
            createdBy:"",
            balance: 0,
            status: "已认证",
             utype  : "用户"
           
        },
        {
            title: "县财政局",
            createdAt: faker.date.recent(),
            userId: "caizhengju",
            av:f_av2,
            avatar: f_avatar2,//"https://s3.amazonaws.com/uifaces/faces/twitter/brenmurrell/128.jpg",
            desc: "负责扶贫资金发放审批",
            createdBy:"",
            balance: 0,
            status : "已认证",
             utype : "用户"
        },
       /* {
            title: "县银行",
            createdAt: faker.date.recent(),
            userId: "yinhang",
            av:f_av3,
            avatar: f_avatar3,//"https://s3.amazonaws.com/uifaces/faces/twitter/brenmurrell/128.jpg",
            desc: "负责扶贫资金的发放",
            createdBy:"",
            balance: 0,
            status : "已认证",
             utype : "用户"
        },*/
        {
            title: "村民",
            createdAt: faker.date.recent(),
            userId: "cunmin",
            av:f_av4,
            avatar: f_avatar4,//"https://s3.amazonaws.com/uifaces/faces/twitter/brenmurrell/128.jpg",
            desc: "负责扶贫项目对象",
            createdBy:"",
            balance: 0,
            status : "已认证",
             utype : "用户"
        }
        /*,
        {
            title: "村",
            createdAt: faker.date.recent(),
            userId: "cun",
            avatar: "https://s3.amazonaws.com/uifaces/faces/twitter/brenmurrell/128.jpg",
            desc: "负责落实扶贫项目",
            createdBy:"",
            balance: 0,
            status : "已认证",
             utype  : "用户"
            
        }*/
    ];


    //创建根帐号，然后用根账号创建其他账号
   /* let uid0=faker.finance.bitcoinAddress();
    fus[0]={
            title: faker.name.findName(),
            createdAt: faker.date.recent(),
            userId: uid0,
            avatar: faker.image.avatar(),
            desc: faker.name.jobDescriptor(),
            createdBy:uid0,
            balance: 0,
        };
    for(var i=1; i<count_user; i++){
        fus[i]={
            title: faker.name.findName(),
            createdAt: faker.date.recent(),
            userId: faker.finance.bitcoinAddress(),
            avatar: faker.image.avatar(),
            desc: faker.name.jobDescriptor(),
            createdBy:uid0,
            balance: 0,
        }
        //console.log(fus[i]);
    }
    
    //假定user0为当前用户
    let fts=[];
    fus.forEach((usrf) => {
        fus.forEach((usrt) => {
            if(usrf!=usrt){
                for(var i=0; i<count_trans; i++){
                    let tid = faker.finance.bitcoinAddress();
                    let cid = faker.finance.bitcoinAddress();
                    let title = faker.finance.transactionType();
                    let dt_confirm = faker.date.recent();
                    let dt_create  = new Date(dt_confirm.getTime());
                    dt_create.setDate(dt_create.getDate() - 3);

                    let ft0 = {
                        transactionId:tid,
                        title: title,
                        createdAt:dt_create,
                        userFrom: usrf.userId,
                        avatarFrom: usrf.avatar,
                        titleFrom: usrf.title,
                        avatarTo: usrt.avatar,
                        titleTo: usrt.title,
                        userTo: usrt.userId,                        
                        data:{'payment':520},
                        desc:faker.lorem.sentence(),                        
                    };
                    ft0.data={'payment':520};
                    fts.push(ft0);
                    //留一些待确认
                    if(i<count_trans-count_unconfirm){
                        ft0.confirmAt= dt_confirm;
                        fts.push({
                            transactionId:cid,
                            confirmId:tid,
                            title: '[确认]'+title,
                            createdAt:dt_confirm,
                            userFrom: usrt.userId,
                            avatarFrom: usrt.avatar,
                            titleFrom: usrt.title,
                            userTo: usrf.userId,
                            avatarTo: usrf.avatar,
                            titleTo: usrf.title,
                            desc:faker.lorem.sentence(),
                            data:{'payment':520},
                        });                   
                    }
                }
            }
        });
    });
    */
    fus.forEach((usr) => {
       Users.insert(usr);
       console.log(usr);
    });
    /*fts.forEach((trans) => {
       Transactions.insert(trans);
       console.log(trans);
    });*/
    if(path_avatar){
        downloadAvatars();   
    }
    return fus[0];
}   